package cn.liuweiwei.controller;


import cn.liuweiwei.domain.FriendLink;
import cn.liuweiwei.service.FriendLinkService;
import cn.liuweiwei.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("links")
@CrossOrigin
public class FriendLinkController {

    @Autowired
    private FriendLinkService friendLinkService;

    /**
     * 分页查询友链列表
     *
     * @param page  当前页
     * @param limit 每页条数
     * @return 友链列表的分页数据
     */
    @GetMapping
    public Result findAllLink(String page, String limit) {
        PageInfo<FriendLink> pageInfo = friendLinkService.findAllLink(page, limit);
        return Result.successWithCodeAndObj(pageInfo);
    }

    /**
     * 添加一个友链
     *
     * @param link
     * @return
     */
    @PostMapping
    public Result insertOneLink(@RequestBody FriendLink link) {
        try {
            friendLinkService.insertOneLink(link);
            return Result.success("添加友链成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加友链失败");
        }
    }

    /**
     * 更新一个友链
     *
     * @param link
     * @return
     */
    @PutMapping
    public Result updateLink(@RequestBody FriendLink link) {
        try {
            friendLinkService.updateLink(link);
            return Result.success("更新友链成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新友链失败");
        }
    }

    /**
     * 通过友链 id 删除友链
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result deleteLink(@PathVariable("id") String id) {
        try {
            friendLinkService.deleteLink(id);
            return Result.success("删除友链成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除友链失败");
        }
    }

}
